// file: pedal.c
// author: Sebastian Steppeler copyright 2012
/*license: This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.*/
#include <avr/io.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <util/delay.h>
#include <util/twi.h>
#include <avr/wdt.h>
#include <avr/interrupt.h>
#include "typedefs.h"
#include "ADC.h"
#include "eeprom.h"
#include "pedal.h"
#include "Midi.h"
#include "main.h"



// globals:
PEDAL Pedals[3];
volatile int8_t cPolarity = 1;

volatile char bNewSample;
volatile int iSampleExchange[8];
int iCurrentSample[8];
int iLastSample[8];
char cLastValue[8];

// pedals: 0= sostenuto 1=soft 2=hold

void RecalcPedalFactors(void)
{
	char n;
	for(n=0;n<3;n++)
		Pedals[(int)n].iFactor = (Pedals[(int)n].iMax-Pedals[(int)n].iMin) / 8;	
}

UCHAR HandlePedal(char cChannel)
{
	int iMidiValue;

	iMidiValue = iCurrentSample[(int)cChannel] - Pedals[(int)cChannel].iMin;
	if(iMidiValue>0)
	{
		iMidiValue *= 16;
		iMidiValue /= Pedals[(int)cChannel].iFactor;
		if(iMidiValue>127)
			iMidiValue = 127;
	}
	else
		iMidiValue = 0;
	
	if((char)iMidiValue==cLastValue[(int)cChannel])
		return 255;
	
	cLastValue[(int)cChannel] = (char)iMidiValue;
	return (UCHAR)iMidiValue;
}

void FetchSample(void)
{
	char n;
	// transfer sample data into calculation buffers:
	cli();
	for(n=0;n<8;n++)
	{
		iLastSample[(int)n] = iCurrentSample[(int)n];
		iCurrentSample[(int)n] = iSampleExchange[(int)n];
	}
	sei();
	bNewSample = false;
	
	return;
}

void CalcPedals(void)
{
	
	UCHAR cMidiValue;
	
	// transfer sample data into calculation buffers:
	FetchSample();
	
	
	cMidiValue = HandlePedal(0);
	if(cMidiValue<128)
		SendMidiCommand(0xB0, 0, PEDAL_CC, cMidiValue);
	
	/*cMidiValue = HandlePedal(1);
	if(cMidiValue<128)
		SendControlAction(PDP_PEDAL_SOFT, cMidiValue);
	
	cMidiValue = HandlePedal(0);
	if(cMidiValue<128)
		SendControlAction(PDP_PEDAL_SOSTENUTO, cMidiValue);
			
	//SendControlAction(PDP_PEDAL_SUSTAIN, 10);*/
	
	_delay_ms(PEDAL_PERIOD_MS);
}
